import axios from './axios'

export interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
}

export interface LoginRequest {
  username: string
  password: string
}

export interface RegisterRequest {
  username: string
  password: string
  email: string
  phone: string
}

export interface UserInfo {
  id: number
  username: string
  email: string
  phone: string
  createTime: string
  updateTime: string
}

interface ChatResponse {
  conversationId: number
  message: {
    role: 'assistant'
    content: string
  }
}

interface SSEOptions {
  onMessage?: (content: string) => void
  onConversationId?: (id: number) => void
  timeout?: number
}

export const api = {
  // 用户相关 API
  async login(data: LoginRequest): Promise<string> {
    return axios.post('/users/login', data)
  },

  async register(data: RegisterRequest): Promise<UserInfo> {
    return axios.post('/users/register', data)
  },

  async getUserInfo(id: number): Promise<UserInfo> {
    return axios.get(`/users/${id}`)
  },

  // 聊天相关 API
  async sendMessage(message: string, conversationId?: number, options: SSEOptions = {}): Promise<void> {
    // 构建 SSE URL，包含所有必要参数
    const url = '/chat' + (conversationId ? `?conversationId=${conversationId}` : '')
    
    return new Promise((resolve, reject) => {
      const timeoutId = setTimeout(() => {
        eventSource.close()
        reject(new Error('请求超时'))
      }, options.timeout || 30000)

      // 创建 EventSource 实例
      const eventSource = new EventSource(url, {
        withCredentials: true
      })

      // 处理消息事件
      eventSource.addEventListener('message', (event) => {
        try {
          const data = JSON.parse(event.data)
          console.log('收到消息片段:', data)
          if (typeof data === 'string') {
            options.onMessage?.(data)
          }
        } catch (error) {
          console.error('解析消息失败:', error)
        }
      })

      // 处理会话ID事件
      eventSource.addEventListener('conversationId', (event) => {
        try {
          const id = JSON.parse(event.data)
          console.log('新会话ID:', id)
          options.onConversationId?.(id)
        } catch (error) {
          console.error('解析会话ID失败:', error)
        }
      })

      // 处理连接打开
      eventSource.onopen = () => {
        console.log('SSE连接已建立')
      }

      // 处理错误
      eventSource.onerror = (error) => {
        console.error('SSE错误:', error)
        clearTimeout(timeoutId)
        eventSource.close()
        reject(error)
      }

      // 处理完成事件
      eventSource.addEventListener('complete', () => {
        console.log('对话完成')
        clearTimeout(timeoutId)
        eventSource.close()
        resolve()
      })

      // 发送初始消息
      fetch(url, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          message,
          history: [] // 如果需要可以传入历史消息
        })
      }).catch(error => {
        clearTimeout(timeoutId)
        eventSource.close()
        reject(error)
      })
    })
  },

  async getChatHistory(conversationId: number): Promise<ChatMessage[]> {
    return axios.get(`/chat/conversations/${conversationId}`)
  }
} 